package com.zzl.mine.util;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zzl.mine.tool.MD5Util;

/**
 * 支付工具类
 * @author wang
 * 2018年5月30日
 */
public class PayUtil {
	
	static Logger logger = LoggerFactory.getLogger(PayUtil.class);

	/**
	 * 计算签名
	 * @param map
	 * @param apiKey
	 * @return
	 */
	public static String sign(Map<String, String> map, String apiKey) {
		String content = buildSignContent(map, apiKey);
		return createSignByMD5(content);
	}

	/**
	 * 拼装待计算签名内容字符串
	 * @param map 参数
	 * @param apiKey key
	 * @return
	 */
	private static String buildSignContent(Map<String, String> map, String apiKey) {
		StringBuffer sb = new StringBuffer();
		for (Entry<String, String> e : map.entrySet()) {
			if (StringUtils.isBlank(e.getKey()))
				continue;

			if ("sign".equals(e.getKey().trim()))// 签名排除sign
				continue;

			if ("class".equals(e.getKey().trim()))// 签名排除class,防止object转map获取多余的key
				continue;

			if (StringUtils.isBlank(e.getValue()))
				continue;

			sb.append(e.getKey());
			sb.append("=");
			sb.append(e.getValue());
			sb.append("&");
		}
		sb.append("key=").append(apiKey);

		logger.debug("waiting pay sign:[{}]", sb.toString());
		return sb.toString();
	}

	/**
	 * 使用MD5方式生成签名
	 * @param content
	 * @return
	 */
	private static String createSignByMD5(String content) {
		// String md5 = MD5Util.encodeMD5Hex(content);
		String md5 = MD5Util.MD5(content);
		return StringUtils.isBlank(md5) ? StringUtils.EMPTY : md5.toUpperCase();
	}

	/**
	 * 验签
	 * @param map
	 * @return
	 */
	public static boolean verifySign(Map<String, String> map, String apiKey) {
		if (null == map || map.isEmpty()) {
			logger.error("verify sign error: map is empty.");
			return Boolean.FALSE;
		}

		String sign = map.get("sign");
		if (StringUtils.isBlank(sign)) {
			logger.error("response missing sign node.");
			return Boolean.FALSE;
		}

		String verifySign = sign(map, apiKey);
		if (StringUtils.isBlank(verifySign)) {
			logger.error("create verify sign failure.");
			return Boolean.FALSE;
		}

		return sign.equals(verifySign);
	}
}
